//
//  ViewController.swift
//  TwitterSearchDemo
//
//  Created by lanou on 16/1/9.
//  Copyright © 2016年 lanou. All rights reserved.
//

import UIKit

let kWidth = UIScreen.mainScreen().bounds.size.width
let kHeight = UIScreen.mainScreen().bounds.size.height

class ViewController: UIViewController, UISearchResultsUpdating, UISearchBarDelegate {

    var searchController: UISearchController?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: Selector("setSearch"))
        
        self.setPrompt()
        self.setBackView()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    //跳出搜索
    func setSearch() {
        self.searchController = UISearchController(searchResultsController: nil)
        self.searchController?.searchResultsUpdater = self
        self.searchController?.dimsBackgroundDuringPresentation = false
        self.searchController?.hidesNavigationBarDuringPresentation = false
        self.searchController?.searchBar.placeholder = "请输入热词"
        self.searchController?.searchBar.delegate = self
        
        self.navigationController?.presentViewController(self.searchController!, animated: true, completion: nil)
    }
    func updateSearchResultsForSearchController(searchController: UISearchController) {
        
    }
    //背景图
    func setBackView()
    {
       let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: kWidth, height: kWidth))
        imageView.center = CGPoint(x: kWidth / 2, y: kHeight / 2)
        imageView.image = UIImage(named: "twitter")
        self.view.addSubview(imageView)
    }
    
    //提示
    func setPrompt() {
        let alert = UIAlertController(title: "提示", message: "请先打开VPN 搜索在右上角哦", preferredStyle: UIAlertControllerStyle.Alert)
        let cancelAction = UIAlertAction(title: "确定", style: UIAlertActionStyle.Cancel, handler: nil)
        alert.addAction(cancelAction)
        self.navigationController?.presentViewController(alert, animated: true, completion: nil)
    }
    
    //搜索返回代理方法
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        let result = searchBar.text!.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())//UTF8
        let urlString = "https://api.twitter.com/1.1/search/tweets.json?q=\(result!)"
        self.searchController?.dismissViewControllerAnimated(true, completion: nil)
        
        let showTVC = ShowTableViewController()
        showTVC.urlString = urlString
        self.navigationController?.pushViewController(showTVC, animated: true)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

